/* eslint-disable no-console */
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import Navigation from 'vue-navigation';
import VueI18n from 'vue-i18n';
import moment from 'vue-moment';
import router from './router';
import store from './store';
import rtXpc from 'vue-xpc';
import App from './App';
import './assets/icons';
import VueKeycloakJs from '@dsb-norge/vue-keycloak-js';
import axios from 'axios';
import lookupFetch from './config/lookup-fetch';

Vue.prototype.$http = Vue.http = axios;

Vue.config.productionTip = false;
Vue.config.debug = true;
Vue.config.devtools = true;

Vue.use(VueI18n);
Vue.use(moment);
Vue.use(Navigation, { router, keyName: 'key' });

axios.defaults.baseURL = process.env.HOST_URL;

getKeyCloakConfig();

//通过租户Code获取KeyCloak配置信息
function getKeyCloakConfig() {
  rt.get('api/keyconf/').then(res => {
    if (res) {
      Vue.use(VueKeycloakJs, {
        init: {
          onLoad: 'login-required',
          checkLoginIframe: false
        },
        config: res,
        onReady: keycloak => {
          if (keycloak) {
            keycloak
              .loadUserProfile()
              .success(profile => {
                initLanguage(profile);
              })
              .error(error => {});
          } else {
            window.location.reload();
          }
        }
      });
    }
  });
}

function initLanguage(profile) {
  let defaultLang = null;
  if (profile.attributes) {
    let lang = profile.attributes.locale;
    if (lang) {
      //获取KC登录用户选择的语言
      defaultLang = lang[0];
    }
  }

  console.log('defaultlang:' + defaultLang);
  const i18n = new VueI18n();
  const opts = {
    config: {
      address: {
        provinceUrl: 'api/citydata/province/queryall',
        cityUrl: 'api/citydata/city/queryall',
        countyUrl: 'api/citydata/county/queryall',
        alias: { id: 'Id', name: 'Name' }, // 别名
        autoLoad: true // 是否自动加载省市县数据
      }
      // // 默认多语言语种名称
      // defaultLocale: 'en-US',
      // // 获取多语言语种 url
      // localesUrl: 'openapi/PortalLanguage/GetLanguageList',
      // // 获取多语言语言包 url
      // localesMessageUrl: 'openapi/PortalLanguage/GetLanguageConfigs?langId='
    }
  };

  Vue.use(rtXpc, opts);

  Vue.lookup.resetFetch(lookupFetch);
  initVue(i18n);
}

function initVue(i18n) {
  new Vue({
    el: '#app',
    router,
    store,
    // i18n,
    components: { App },
    template: '<App/>'
  });
}
